import base64
import datetime

import pytz
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from rest_framework import exceptions, status
from rest_framework.authentication import BaseAuthentication
# Create your views here.
from django.core.cache import cache
import time
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from datetime import datetime, timedelta
from myapp import models
from django.http import JsonResponse
from rest_framework.views import APIView
from itertools import groupby
from myapp.models import userToken


class AuthView(APIView):

    def post(self, request, *args, **kwargs):
        ret = {'code': 1000, 'msg': None}
        usr = request.data.get('username')
        pas = request.data.get('password')
        print(usr)
        print(pas)
        obj = models.User.objects.filter(username=usr, password=pas).first()
        if not obj:
            ret['code'] = '1001'
            ret['msg'] = '用户名或者密码错误'
            raise APIException(ret)
            # 里为了简单，应该是进行加密，再加上其他参数
        token = str(time.time()) + usr
        print(token)
        # try:
        # models.userToken.objects.update_or_create(username=obj, defaults={'token': token,'create_time':datetime.now()})
        models.userToken.objects.update_or_create(username=obj,defaults={'token': token})
        ret['msg'] = '登录成功'
        ret['token'] = token
        # except Exception as e:
        #     ret['code'] = 1003
        #     ret['msg'] = '该账号已经登录,退出后可再登陆'
        return JsonResponse(ret)


class LoginOutView(APIView):

    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        print(token)
        ret = {'code': 1000, 'msg': None}
        obj = models.userToken.objects.filter(token=token).first()
        if not obj:
            ret['code'] = 1005
            ret['msg'] = 'token与数据库不匹配'
            raise APIException(ret)
        try:
            models.userToken.objects.get(token=token).delete()
            ret['msg'] = '退出成功，token清除'
        except Exception as e:
            ret['code'] = 1006
            ret['msg'] = 'token删除失败'
        return JsonResponse(ret)


class AuthcationView(BaseAuthentication):

    def authenticate(self, request):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')  # 将token放入请求头中
            print(token)
        except Exception as e:
            ret = {'code': 1007, 'msg': '未获取到token，请重新登陆'}
            raise APIException(ret)
        user = cache.get(token)
        if user:
            print('这是缓存')
            return user, token
        token_obj = userToken.objects.filter(token=token).first()
        if not token_obj:
            ret = {'code': 1007, 'msg': 'token错误，请重新登陆'}
            raise APIException(ret)
        created_time = token_obj.create_time
        print('创建时间', created_time)
        now_time = datetime.now()
        print('现在的时间', now_time)
        delta = now_time - created_time
        print('过去多少天时间', delta)
        if delta < timedelta(hours=5):
            remain_time = timedelta(hours=5) - delta
            print('剩余时间', remain_time)
            cache.set(token_obj.token, token_obj.username_id, min(remain_time.total_seconds(), 3600 * 24 * 7))
            print('这是数据库')
            return token_obj.username_id, token
        else:
            ret = {'code': 1007, 'msg': 'token过期，请重新登陆'}
            userToken.objects.filter(token=token).delete()
            raise APIException(ret)

    def authenticate_header(self, request):
        pass

class Authcation_NomalView(BaseAuthentication):

    def authenticate(self, request):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')  # 将token放入请求头中
            print(token)
        except Exception as e:
            ret = {'code': 1007, 'msg': '未获取到token，请重新登陆'}
            raise APIException(ret)
        if token:
            user_name = [''.join(list(g)) for k, g in groupby(token, key=lambda x: x.isdigit())]
            username = user_name[3].split('@')[0]
            print(username)
            if username  not in ['sun','hexu']:
                ret = {'code': 1008, 'msg': '该用户无权限! '}
                #raise APIException(ret)
                return Response(ret)
        user = cache.get(token)
        if user:
            print('这是缓存')
            return user, token
        token_obj = userToken.objects.filter(token=token).first()
        if not token_obj:
            ret = {'code': 1007, 'msg': 'token错误，请重新登陆'}
            raise APIException(ret)
        created_time = token_obj.create_time
        print('创建时间', created_time)
        now_time = datetime.now()
        print('现在的时间', now_time)
        delta = now_time - created_time
        print('过去多少天时间', delta)
        if delta < timedelta(hours=5):
            remain_time = timedelta(hours=5) - delta
            print('剩余时间', remain_time)
            cache.set(token_obj.token, token_obj.username_id, min(remain_time.total_seconds(), 3600 * 24 * 7))
            print('这是数据库')
            return token_obj.username_id, token
        else:
            ret = {'code': 1007, 'msg': 'token过期，请重新登陆'}
            userToken.objects.filter(token=token).delete()
            raise APIException(ret)


    def authenticate_header(self, request):
        pass
